import { Game } from './core/Game';
import { MenuManager } from './systems/MenuManager';
import { MenuRenderer } from './systems/MenuRenderer';
import { SkinSystem } from './systems/SkinSystem';
import { ProgressionManager } from './systems/ProgressionManager';

class GameEngine {
    private game: Game;
    private lastTime: number = 0;
    private accumulator: number = 0;
    private readonly timestep: number = 1000 / 60; // 60 FPS

    constructor() {
        this.game = new Game();
        this.init();
    }

    private init(): void {
        // 启动游戏循环
        requestAnimationFrame((timestamp) => this.gameLoop(timestamp));
    }

    private gameLoop(currentTime: number): void {
        if (this.lastTime === 0) {
            this.lastTime = currentTime;
        }

        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;
        this.accumulator += deltaTime;

        // 固定时间步长更新
        while (this.accumulator >= this.timestep) {
            this.game.update(this.timestep);
            this.accumulator -= this.timestep;
        }

        // 渲染
        this.game.render();

        // 继续游戏循环
        requestAnimationFrame((timestamp) => this.gameLoop(timestamp));
    }
}

// 当DOM加载完成后启动游戏
document.addEventListener('DOMContentLoaded', () => {
    new GameEngine();
});

// 初始化游戏画布
const canvas = document.getElementById('gameCanvas') as HTMLCanvasElement;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// 创建皮肤系统、进度管理器和菜单管理器
const skinSystem = new SkinSystem();
const progressionManager = new ProgressionManager();
const menuManager = new MenuManager(skinSystem, progressionManager);
const menuRenderer = new MenuRenderer(canvas, menuManager);

// 监听窗口大小变化
window.addEventListener('resize', () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
});